{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "r28eBle5gBRb"
   },
   "source": [
    "# Finetuner un modèle avec Keras"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "N87zfVrxgBRe"
   },
   "source": [
    "Installez les bibliothèques 🤗 Transformers et 🤗 Datasets pour exécuter ce notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "utBT47KIgBRf"
   },
   "outputs": [],
   "source": [
    "!pip install datasets transformers[sentencepiece]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "FJ-ImuKtgBRg"
   },
   "outputs": [],
   "source": [
    "from datasets import load_dataset\n",
    "from transformers import AutoTokenizer, DataCollatorWithPadding\n",
    "import numpy as np\n",
    "\n",
    "raw_datasets = load_dataset(\"paws-x\", \"fr\")\n",
    "checkpoint = \"camembert-base\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(checkpoint)\n",
    "\n",
    "\n",
    "def tokenize_function(example):\n",
    "    return tokenizer(example[\"sentence1\"], example[\"sentence2\"], truncation=True)\n",
    "\n",
    "\n",
    "tokenized_datasets = raw_datasets.map(tokenize_function, batched=True)\n",
    "\n",
    "data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors=\"tf\")\n",
    "\n",
    "tf_train_dataset = tokenized_datasets[\"train\"].to_tf_dataset(\n",
    "    columns=[\"attention_mask\", \"input_ids\", \"token_type_ids\"],\n",
    "    label_cols=[\"labels\"],\n",
    "    shuffle=True,\n",
    "    collate_fn=data_collator,\n",
    "    batch_size=8,\n",
    ")\n",
    "\n",
    "tf_validation_dataset = tokenized_datasets[\"validation\"].to_tf_dataset(\n",
    "    columns=[\"attention_mask\", \"input_ids\", \"token_type_ids\"],\n",
    "    label_cols=[\"labels\"],\n",
    "    shuffle=False,\n",
    "    collate_fn=data_collator,\n",
    "    batch_size=8,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "411-vGP8gBRi"
   },
   "outputs": [],
   "source": [
    "from transformers import TFAutoModelForSequenceClassification\n",
    "\n",
    "model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ChcrgFOegBRk"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.losses import SparseCategoricalCrossentropy\n",
    "\n",
    "model.compile(\n",
    "    optimizer=\"adam\",\n",
    "    loss=SparseCategoricalCrossentropy(from_logits=True),\n",
    "    metrics=[\"accuracy\"],\n",
    ")\n",
    "model.fit(\n",
    "    tf_train_dataset,\n",
    "    validation_data=tf_validation_dataset,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "C0p3eZg8gBRl"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.optimizers.schedules import PolynomialDecay\n",
    "\n",
    "batch_size = 8\n",
    "num_epochs = 3\n",
    "# Le nombre d'étapes d'entraînement est le nombre d'échantillons dans le jeu de données, divisé par la taille du batch, puis multiplié par le nombre total d'époques.\n",
    "# Notez que le jeu de données tf_train_dataset est ici un batch de données tf.data.Dataset \n",
    "# et non le jeu de données original Hugging Face, donc sa len() est déjà num_samples // batch_size.\n",
    "num_train_steps = len(tf_train_dataset) * num_epochs\n",
    "lr_scheduler = PolynomialDecay(\n",
    "    initial_learning_rate=5e-5, end_learning_rate=0.0, decay_steps=num_train_steps\n",
    ")\n",
    "from tensorflow.keras.optimizers import Adam\n",
    "\n",
    "opt = Adam(learning_rate=lr_scheduler)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "oM6s7MDmgBRl"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)\n",
    "loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n",
    "model.compile(optimizer=opt, loss=loss, metrics=[\"accuracy\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "gJhWFti0gBRm"
   },
   "outputs": [],
   "source": [
    "model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "k5DiX0KegBRn"
   },
   "outputs": [],
   "source": [
    "preds = model.predict(tf_validation_dataset)[\"logits\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1VvLVrOmgBRo"
   },
   "outputs": [],
   "source": [
    "class_preds = np.argmax(preds, axis=1)\n",
    "print(preds.shape, class_preds.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5xL_iSCXgBRp"
   },
   "outputs": [],
   "source": [
    "from datasets import load_metric\n",
    "\n",
    "metric = load_metric(\"glue\", \"mrpc\")\n",
    "metric.compute(predictions=class_preds, references=raw_datasets[\"validation\"][\"label\"])"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
